// pages/courseDetail/courseDetail.js
var app = getApp();
var util=require("../../utils/util");
var home=require("../../api/home");
var config=require("../../api/config");
var canvas=require("../../utils/canvas")

Page({
  /*页面的初始数据*/
  data: {
    width: wx.getSystemInfoSync().windowWidth,
    id: '',
    info: '',
    navColor: 'rgba(0,0,0,0)',
    title: '',
    point: '',
    back_type: 1,
    banner_list: [1,2,3],
    current_index: 0,
    scroll_top: [],
    toView: '',
    bar_text: ["课程概况","课程特色","授课老师","课程评价","课程机构","课程详情","购买须知"],
    pref_text: ['立减券','满减券','礼品券','','平台券'],
    bar_index: 0,
    fix: false,
    pop_show: true,
    com_data: [],
    show_com: 0,
    more_survey_cont: false,
    more_char_cont: false,
    comment_list: [],
    pref_list: [],
    currentPage: 1,
    pageSize: 10,
    hasMoreDate: true,
    latitude: 22.820794,
    longitude: 113.284565,
    token: '',
    userinfo: '',
    diff_height: 0,
    login_mask: true,
    show_share: true,
    hold: true,
    ensure: true,
    canvasBg: 'https://ossdev0.jiabala.com/bFRrHfctJsRpj',
    ewm: 'https://ossdev0.jiabala.com/dpD3Bi4n6GXCW',
    businessSer:[{icon:'/images/icon162.png',title:'实时保障'},{icon:'/images/icon163.png',title:'五星辅导'},{icon:'/images/icon164.png',title:'放心学习'}],
    parentId: '',
    com_money: ''
  },
  // 监听页面加载
  onLoad: function (options) {
    var that=this,id=options.id?options.id:decodeURIComponent(options.scene);
    if(options.type){
      that.setData({back_type:options.type})
    }
    if(options.parentId){
      that.setData({parentId:options.parentId})
    }
    var sysInfo = wx.getSystemInfoSync();
    var pixelRate = sysInfo.windowWidth / 750,times=sysInfo.windowWidth/375;
    that.setData({id:id,top_height: (sysInfo.statusBarHeight+44)/pixelRate,times:times,width: sysInfo.windowWidth});
    wx.getStorage({
      key: 'city',
      success:function(res){
        var info=res.data;
        that.setData({latitude:info.lat,longitude:info.lng})
        that.get_cour_detail(id)
      },
      fail:function(){
        that.get_cour_detail(id)
      },
    })
    //
    that.cour_browse(id)
    var status=options.status?options.status:0,key=["未知","首页","名师详情","兴趣教育","学科辅导","机构详情","搜索","我的订单","我的收藏"]
    // 事件统计
    app.td_app_sdk.event({
      id: 'courseDetail',
      label: '课程详情',
      params: {
        key1: key[status]
      }
    })
    //下载图片
    // Promise.all([
    //   util.downLoadImg(that.data.canvasBg),
    //   util.downLoadImg(that.data.ewm)
    // ]).then(res=>{
    //   that.setData({img1:res[0].tempFilePath,img5:res[1].tempFilePath})
    // })
  },
  // 轮播图
  swiper_change:function(e){
    this.setData({current_index: e.detail.current})
  },
  // 放大预览图片
  preview_img:function(e){
    var that=this,info=that.data.info;
    var src=e.currentTarget.dataset.src;
    wx.previewImage({
      current: src,
      urls: info.swipers
    })
  },
  // 查看更多
  open_more:function(e){
    var that = this;
    var num = e.currentTarget.dataset.num;
    if(num==1){
      that.setData({more_survey_cont:true})
    }else{
      that.setData({more_char_cont:true})
    }
  },
  enshow:function(){
    this.setData({ensure:!this.data.ensure})
  },
  // 页面滚动
  page_scroll:function(e){
    var that = this,scroll_top = that.data.scroll_top,top_height = that.data.top_height,bar_index=that.data.bar_index,diff_height=that.data.diff_height,scroll_index=that.data.bar_index;
    var scroll = e.detail.scrollTop,info=that.data.info;
    // console.log(scroll)
    if(scroll >= 160){
      that.setData({navColor: '#ffffff',title:info.name,point: info.courseNatureName})
    }else{
      that.setData({navColor: 'rgba(0,0,0,0)',title:'',point: ''})
    }
    if(scroll_top.length>0){
      if(scroll>=(scroll_top[0].top-top_height)){
        if(!that.data.fix){
          that.setData({fix: !that.data.fix})
        }
      }else{
        if(that.data.fix){
          that.setData({fix: !that.data.fix})
        }
      }
      for (var i = 0; i < scroll_top.length; i++) {
        if ((i + 1) < scroll_top.length&&i>0) {
          if (scroll > (scroll_top[i-1].top-diff_height) && scroll < (scroll_top[i].top-diff_height)) {
            scroll_index=i
          }
        }
        if (scroll < scroll_top[0].top-diff_height) {
          scroll_index=0
        }
      }
    }
    that.setData({ bar_index: scroll_index })
    if(bar_index!=scroll_index){
      that.scroll_to_left(scroll_index)
    }
  },
  // 顶部导航
  scroll_page_to:function(e){
    var that = this,bar_index=that.data.bar_index,bar_text=that.data.bar_text,scroll_top=that.data.scroll_top;
    var index = e.currentTarget.dataset.index;
    if(bar_index != index){
      that.setData({bar_index:index})
      if(index==(bar_text.length-1)){
        that.setData({scroll_to_top:scroll_top[index].top})
      }else{
        that.setData({toView:"item"+(index+1)})
      }
    }
    //切换
    that.scroll_to_left(index)
  },
  // 顶部导航滑动
  scroll_to_left:function(index){
    var that=this,len=that.data.bar_text.length,bar_text=that.data.bar_text;
    if(len >= 3){
      var curWidth = (that.data.width - 30) / 4.5;
      var moveWidth = (index - 1) * curWidth
      if (moveWidth > 0) {
        that.setData({ scrollLeft: parseInt(moveWidth)})
      } else {
        that.setData({ scrollLeft: 0 })
      }
    }
  },
  // 渲染完成
  onReady: function () {
    this.dialog = this.selectComponent('#courpop');
  },
  // 分享
  onShareAppMessage:function(e){
    // 事件统计
    app.td_app_sdk.event({
      id: 'courseDetailEvent',
      label: '课程详情',
      params: {
        key1: "分享"
      }
    })
    var that=this,parentId='',info=that.data.info,userinfo=that.data.userinfo;
    if(info.id){that.cour_share(info.id)}
    if(userinfo){parentId=userinfo.id}
    return{
      title: info.name,
      path: '/pages/courseDetail/courseDetail?id='+info.id+'&type=2&parentId='+parentId,
      imageUrl: info.swipers[0]
    }
  },
  onShareTimeline:function(){
    var that=this,info=that.data.info;
    return{
      title: info.name,
      query: 'id='+info.id+'&type=2',
      imageUrl: info.swipers[0]
    }
  },
  // 页面刷新
  onShow:function(){
    var that=this,token=that.data.token,id=that.data.id;
    var token_again=wx.getStorageSync('token'),userinfo=wx.getStorageSync('userinfo');
    if(!token&&token_again){
      that.setData({token:token_again,userinfo:userinfo})
      // util.downLoadImg(userinfo.avatar).then(res=>{
      //   that.setData({img4:res.tempFilePath})
      // })
    }
    if(app.globalData.login||app.globalData.change_courMeal){
      that.get_cour_detail(id)
      app.globalData.login=false;
      app.globalData.change_courMeal=false;
      app.globalData.change_dom=false;
      app.globalData.change_table=false;
    }
  },
  // 弹窗
  open_courpop:function(e){
    var that = this,info=that.data.info,token=that.data.token;
    var num = e.currentTarget.dataset.num;
    if(num==1){
      that.setData({com_data:that.data.pref_list,currentPage:1})
    }else if(num==2){
      var info_data={score:'',commentCount:''};
      info_data.score=info.sumScore,info_data.commentCount=info.commentCount
      that.setData({com_data:that.data.comment_list,info_data:info_data,currentPage:1})
    }else if(num==3){
      that.setData({com_data:info.courseProtocolTemplate})
      // 事件统计
      app.td_app_sdk.event({
        id: 'courseDetailEvent',
        label: '课程详情',
        params: {
          key1: "购买须知"
        }
      })
    }else if(num==4){
      that.setData({com_data:info.courseSetMeals})
      // 事件统计
      app.td_app_sdk.event({
        id: 'courseDetailEvent',
        label: '课程详情',
        params: {
          key1: "课程报名"
        }
      })
    }else if(num==5){
      if(!token){
        that.setData({login_mask:false})
        return false;
      }
    }
    that.setData({show_com:num,pop_show: !that.data.pop_show})
  },
  close_pop:function(e){
    var that = this;
    var obj = e.detail.pop_show;
    that.setData({pop_show: obj})
  },
  // 
  nav_detail:function(){
    wx.navigateTo({
      url: '../courDet/courDet',
    })
  },
  // 领取优惠卷
  get_pref:function(e){
    var that=this,pref_list=that.data.pref_list,token=that.data.token;
    var index=e.detail.index;
    if(pref_list[index].isReceive!=1){
      if(token){
        //
        that.user_get_pref(index,token)
      }else{
        that.nav_login()
        that.setData({pop_show: true,pref_list:[]})
      }
    }
  },
  // 联系
  call_phone:function(){
    var that=this,info=that.data.info;
    wx.makePhoneCall({
      phoneNumber: info.businessPhone,
      success:function(){},
      fail:function(){}
    })
    // 事件统计
    app.td_app_sdk.event({
      id: 'courseDetailEvent',
      label: '课程详情',
      params: {
        key1: "电话联系"
      }
    })
  },
  // 老师
  nav_famous:function(){
    var that=this,info=that.data.info;
    if(info.teacherId){
      wx.navigateTo({
        url: '../famousDetail/famousDetail?uid='+info.teacherId+'&oid='+info.businessId+'&type=2',
      })
    }
    // 事件统计
    app.td_app_sdk.event({
      id: 'courseDetailEvent',
      label: '课程详情',
      params: {
        key1: "老师"
      }
    })
  },
  // 机构
  nav_go_mech:function(){
    var that=this,info=that.data.info;
    wx.navigateTo({
      url: '../mechDetail/mechDetail?id='+info.businessId+'&status=1',
    })
    // 事件统计
    app.td_app_sdk.event({
      id: 'courseDetailEvent',
      label: '课程详情',
      params: {
        key1: "机构"
      }
    })
  },
  // 路线
  open_location:function(){
    var that=this,info=that.data.info;
    wx.openLocation({
      latitude: info.businessLat,
      longitude: info.businessLng,
      name: info.businessName,
      address: info.businessAddress,
      success:function(res){
        console.log('---路线---')
      }
    })
    // 事件统计
    app.td_app_sdk.event({
      id: 'courseDetailEvent',
      label: '课程详情',
      params: {
        key1: "地图"
      }
    })
  },
  return:function(){},
  // 触底
  scroll_bottom:function(e){
    var that=this,id=that.data.id,hasMoreData=that.data.hasMoreData;
    var type=e.detail;
    if(hasMoreData){
      if(type==1){
        that.get_pref_list();
      }else{
        that.get_cour_comment(id,1)
      }
    }else{
      util.page_show_toast('没有更多了',1500)
    }
  },
  // 收藏
  user_call_cour:function(){
    var that=this,info=that.data.info,token=that.data.token;
    if(token){
      if(!info.isCollect||info.isCollect==0){
        info.isCollect=1
        info.collectionCount +=1
        that.call_cour(info.id,true,token)
      }else{
        info.isCollect=0
        info.collectionCount -=1
        that.call_cour(info.id,false,token)
      }
      that.setData({info:info})
    }else{
      that.nav_login()
    }
    // 事件统计
    app.td_app_sdk.event({
      id: 'courseDetailEvent',
      label: '课程详情',
      params: {
        key1: "收藏课程"
      }
    })
  },
  // 登录
  nav_login:function(){
    this.close_mask()
    wx.navigateTo({
      url: '../login/login',
    })
  },
  close_mask:function(){
    this.setData({login_mask:true,show_share:true})
  },
  // 详情
  get_cour_detail:function(id){
    wx.showLoading({title: '加载中'})
    var that=this,bar_text=that.data.bar_text;
    var params={
      "id":id,
      "lat": that.data.latitude,
      "lng": that.data.longitude
    }
    home.get_cour_detail(params).then(res=>{
      if(res.data.code==200){
        if(res.data.data){
          var info=res.data.data;
          info.sumScore=info.sumScore?info.sumScore.toFixed(1):'5.0';
          info.swipers=info.introducePictures?info.introducePictures.split(","):'';
          info.courseNatureName=info.courseNatureName?info.courseNatureName.substr(0,2):''
          info.space=info.distance>1000?(info.distance/1000).toFixed(2):info.distance;
          info.overview=''
          info.feature=''
          info.labelName=info.labelName?info.labelName.split(","):'';
          info.teacherProfile=info.teacherProfile?(info.teacherProfile.indexOf("undefined")>-1?'':info.teacherProfile.split(",")):'';
          info.labels=info.labels?info.labels.split(","):'';
          info.collectionCount=info.collectionCount?info.collectionCount:0;
          var details=info.details?info.details:'';
          if(details){
            if(details.indexOf('img')>-1){
              details=details.replace(/\<img/gi, '<img style="max-width:100%;height:auto" ')
            }
            if(details.indexOf('<style>')>-1){
              details=details.replace(/<style>[\s\S]*?<\/style>/ig,'')
            }
            if(details.indexOf('<script>')>-1){
              details=details.replace(/<script>[\s\S]*?<\/script>/ig,'')
            }
          }
          info.details=details;
          info.initialRegistrationCount=info.initialRegistrationCount?info.initialRegistrationCount:0
          for(var i=0;i<info.courseSetMeals.length;i++){
            info.courseSetMeals[i].lessonTime=info.lessonTime
            info.courseSetMeals[i].classTime=info.courseSetMeals[i].classTime?info.courseSetMeals[i].classTime.split(","):''
          }
          for(var m=0;m<bar_text.length;m++){
            if(!info.overview&&bar_text[m]=="课程概况"){
              bar_text.splice(m,1)
            }
            if(!info.feature&&bar_text[m]=="课程特色"){
              bar_text.splice(m,1)
            }
          }
          that.setData({bar_text:bar_text})
          if(info.isSecurityPlan==1){
            var money=Math.max.apply(Math,info.courseSetMeals.map(item => { return item.price }))
            info.courseSetMeals.forEach(item=>{
              if(item.price==money){
                if(item.floorPrice&&item.oneAgent){
                  that.setData({com_money:Math.floor((Number(item.price)-Number(item.floorPrice))*Number(item.oneAgent))})
                }
              }
            })
          }
          //
          that.get_grade_list(info)
          // if(info.logoImg){
          //   util.downLoadImg(info.logoImg).then(res=>{
          //     that.setData({img2:res.tempFilePath})
          //   })
          // }
          // if(info.swipers){
          //   util.downLoadImg(info.swipers[0]).then(res=>{
          //     that.setData({img3:res.tempFilePath})
          //   })
          // }
        }else{
          util.page_show_toast('课程已下架',1500)
        }
      }
    })
  },
  // 适用年级
  get_grade_list:function(cour_info){
    var that=this,info=cour_info;
    config.get_grade_list().then(res=>{
      if(res.data.code==200){
        var list=res.data.data;
        for(var i=0;i<list.length;i++){
          for(var j=0;j<list[i].gradeList.length;j++){
            if(info.gradeBegin==list[i].gradeList[j].value){
              info.gradeBeginName=list[i].gradeList[j].text
            }
            if(info.gradeEnd==list[i].gradeList[j].value){
              info.gradeEndName=list[i].gradeList[j].text
            }
          }
        }
        that.setData({info:info,pref_list:[],diff_height:info.lableName?'30':'60'})
        setTimeout(()=>{
          var query = wx.createSelectorQuery();
          query.selectAll('.page_scroll').boundingClientRect(function (res) {
            // console.log(res)
            that.setData({scroll_top: res})
          }).exec()
        },600)
        //
        that.get_pref_list();
        that.get_cour_comment(cour_info.id,0);
        var cour_details={id:info.id,img:info.swipers[0],name:info.name,courseNatureName:info.courseNatureName,gradeBeginName:info.gradeBeginName,gradeEndName:info.gradeEndName,count:info.initialRegistrationCount,isAgeLimit:info.isAgeLimit,details:info.details};
        wx.setStorageSync('cour_details', cour_details)
      }
    })
  },
  // 优惠券
  get_pref_list:function(){
    var that=this,currentPage=that.data.currentPage,pageSize=that.data.pageSize,pref_text=that.data.pref_text,info=that.data.info;
    var params={
      "businessId": info.businessId,
      "courseId": info.id,
      "currentPage": currentPage,
      "pageSize": pageSize
    }
    home.get_cour_pref_list(params).then(res=>{
      if(res.data.code==200){
        var list=res.data.data.records;
        for(var i=0;i<list.length;i++){
          list[i].couponStartTime=util.formatTime_year(new Date(list[i].couponStartTime))
          list[i].couponEndTime=util.formatTime_year(new Date(list[i].couponEndTime))
          list[i].couponWayName=pref_text[list[i].couponWay]
        }
        var pref_list = that.data.pref_list;
        pref_list = util.extend(pref_list, list)
        if (list.length < pageSize) {
          that.setData({
            pref_list: pref_list,
            hasMoreData: false
          })
        } else {
          that.setData({
            pref_list: pref_list,
            hasMoreData: true,
            currentPage: currentPage + 1
          })
        }
      }
    })
  },
  // 领取优惠券
  user_get_pref:function(index,token){
    wx.showLoading({title: ''})
    var that=this,pref_list=that.data.pref_list,userinfo=that.data.userinfo;
    var params={
      "couponId": pref_list[index].id
    }
    home.get_pref(params,token).then(res=>{
      if(res.data.code==200){
        util.page_show_toast('领取成功',1500)
        pref_list[index].isReceive=1;
        that.setData({pref_list:pref_list,com_data:pref_list})
      }
    })
  },
  // 评论
  get_cour_comment:function(id,type){
    wx.showLoading({title: '加载中'})
    var that=this,currentPage=that.data.currentPage,pageSize=that.data.pageSize;
    var params={
      "courseId": id,
      "currentPage": currentPage,
      "pageSize": pageSize
    }
    home.get_cour_comment(params).then(res=>{
      if(res.data.code==200){
        var list=res.data.data.records;
        for(var i=0;i<list.length;i++){
          list[i].createTime=util.formatTime(new Date(list[i].createTime))
          list[i].score_list=["","","","",""]
        }
        var comment_list = that.data.comment_list;
        comment_list = util.extend(comment_list, list)
        if (list.length < pageSize) {
          that.setData({
            comment_list: comment_list,
            hasMoreData: false
          })
        } else {
          that.setData({
            comment_list: comment_list,
            hasMoreData: true,
            currentPage: currentPage + 1
          })
        }
        if(type==1){
          that.setData({com_data: comment_list})
        }
      }
    })
  },
  // 收藏
  call_cour:function(id,like,token){
    wx.showLoading({title: ''})
    var params={"courseId": id,"isLike": like};
    home.call_cour(params,token).then(res=>{
      if(res.data.code==200){
        if(like){
          util.page_show_toast('收藏成功',2000)
        }else{
          util.page_show_toast('取消收藏成功',2000)
        }
      }
    })
  },
  // 分享
  cour_share:function(id){
    home.cour_share({"id":id}).then(res=>{

    })
  },
  // 浏览
  cour_browse:function(id){
    home.cour_browse({"id":id}).then(res=>{

    })
  },
  // 画布
  canvas_draw:function(){
    var that=this,info=that.data.info,userinfo=that.data.userinfo,bg=that.data.img1,logo=that.data.img2,courImg=that.data.img3,avatar=that.data.img4,ewm=that.data.img5;
    var ctx = wx.createCanvasContext('shareCanvas');
    canvas.canvas_draw(that,info,userinfo,bg,logo,courImg,avatar,ewm,ctx)
  },
  // 保存图片
  confirm_img:function(){
    var that=this,share_img=that.data.share_img;
    wx.saveImageToPhotosAlbum({
      filePath: share_img,
      success(res) {
        util.page_show_toast("保存成功",1500)
      }
    })
  },
  delect_all:function(){
    wx.clearStorage({
      success:function(){
        util.page_show_toast("清除成功",2000)
      },
    })
  },
})